﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExchangeCurrencyRate.Entity;
using System.Net;
using System.Configuration;
using System.IO;

namespace ExchangeCurrencyRate.Export
{
    public class ExchangeRateApiComExporter
    {
        public delegate void ExportAction(string currencyCode1, string currencyCode2, decimal exchangeRate, bool saveResult);
        //
        protected List<string> CurrencyCodeList { get; set; }
        protected CurrencyRateProvider CurrencyRateProvider { get; set; }
        //
        public ExchangeRateApiComExporter(List<string> codeList, CurrencyRateProvider provider)
            : base()
        {
            CurrencyCodeList = codeList;
            CurrencyRateProvider = provider;
        }
        //
        public void Export(DateTime dateTime, ExportAction exportAction)
        {
            foreach (var itemFrom in CurrencyCodeList)
            {
                foreach (var itemTo in CurrencyCodeList.Where(x => !x.Equals(itemFrom)))
                {
                    WebRequest request = HttpWebRequest.Create("http://www.exchangerate-api.com/" + itemFrom + "/" + itemTo + "/1?k=" + ConfigurationManager.AppSettings["ExchangeRateApiComKey"]);
                    {
                        WebResponse response = request.GetResponse();
                        {
                            using (Stream stream = response.GetResponseStream())
                            {
                                using (StreamReader reader = new StreamReader(stream))
                                {
                                    string data = reader.ReadToEnd();
                                    decimal exchangeRate;
                                    if (decimal.TryParse(data, System.Globalization.NumberStyles.Currency, System.Globalization.CultureInfo.InvariantCulture, out exchangeRate))
                                    {
                                        bool saveResult = CurrencyRateProvider.SaveExchangeRate(itemFrom, itemTo, dateTime, exchangeRate);
                                        if (null != exportAction)
                                        {
                                            exportAction.Invoke(itemFrom, itemTo, exchangeRate, saveResult);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
